<?php
class Web_Action_Helper_Pagination 
	extends Zend_Controller_Action_Helper_Abstract
{
	public $limit;
	public $page;
	public $order;
	public $totalItems;
	
	protected $_defaultOrder = 'status';
	protected $_defaultLimit = 10;
	protected $_defaultPage  = 1;
	
	protected $_paginator;
	protected $_adapter;
	protected $_remember;
	protected $_key;
	
	private $_orders = array(
		'status'	=> 'estado',
		'ranking'	=> 'ranking DESC',
		'date'	    => 'fechaCreacion DESC',
		'nameAsc'	=> 'nombre ASC',
		'nameDesc'	=> 'nombre DESC'
	);
	
	public function init()
	{
		$session = Zend_Registry::get('session');
		$this->_remember = $session->{__CLASS__};
		
		$this->order= $this->_orders[$this->getVar('order', $this->_defaultOrder)];
		
		$this->page	= $this->getVar('page', $this->_defaultPage);
		$this->limit= $this->getVar('limit', $this->_defaultLimit);

		$this->offset= ($this->page * $this->limit) - $this->limit;
		
	}
	
	public function setItemsCount( $totalItems )
	{
		$this->totalItems = $totalItems;
		Zend_Paginator::setDefaultItemCountPerPage( $this->limit );
		
		$adapter = new Zend_Paginator_Adapter_Null($totalItems);
		
		$this->_paginator = new Zend_Paginator($adapter);		
		$this->_paginator->setCurrentPageNumber( $this->page );
		
		$this->setVars();
	}
	
	public function setDefaults( $order, $limit )
	{
		$this->_defaultOrder = $order;
		$this->_defaultLimit = $limit;
	
	}
	
	public function remember( $var, $value)
	{
//		$this->_remember[$this->getKey()][$var] = $value;
	}
	
	public function getVar( $var, $default )
	{
		$request = $this->getRequest();
		
		if ( $request->has($var) ){
			$value = $request->getParam($var);	
				
		} elseif( isset($this->_remember[$this->getKey()][$var]) ){
			
			$value = $this->_remember[$this->getKey()][$var];
			
		} else {
			$value = $default;
		}
		
		$this->remember($var, $value);
		return $value;
	}
	
	protected function setVars()
	{
		$view = $this->getActionController()->view;
		
		$view->paginator = $this->_paginator;
		
		$view->limit = $this->limit;
		
		$order = array_search($this->order, $this->_orders);
		$view->orderby = $order;
		$view->order = $order;
		$view->paginator->order = $order;
		$view->page = $this->page;
		$view->totalItems = $this->totalItems;
	}
	
	protected function getKey()
	{
		if ( is_null($this->_key) ){
		
			$controller = $this->getRequest()->getParam('controller');
			$action		= $this->getRequest()->getParam('action');
			$this->_key = "$controller-$action";
		
		}
		
		return $this->_key;
	}
	
	public function __destruct()
	{
		$session = Zend_Registry::get('session');
		$session->{__CLASS__} = $this->_remember;
	}
	
	
	
	
	
}